package se.lixi.wordfind;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;

public class WordfindActivity extends ListActivity {

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				EditText requiredEditText = (EditText) findViewById(R.id.letters);
				String required = requiredEditText.getText().toString();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(requiredEditText.getWindowToken(), 0);
				String prefix = ((EditText) findViewById(R.id.prefix)).getText().toString();
				String middle = ((EditText) findViewById(R.id.middle)).getText().toString();
				String suffix = ((EditText) findViewById(R.id.suffix)).getText().toString();
				new SearchTask().execute(prefix + middle + suffix + required, prefix, middle, suffix);
			}
		});
	}

	private class SearchTask extends AsyncTask<String, Integer, List<String>> {
		private ProgressDialog dialog = new ProgressDialog(WordfindActivity.this);;
		int[] resourcesToLookIn = new int[] { R.raw.dsso1, R.raw.dsso2, R.raw.dsso3, R.raw.dsso4, R.raw.dsso5,
				R.raw.dsso6 };

		@Override
		protected void onPreExecute() {
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setMessage("Searching...");
			dialog.setMax(100);
			dialog.show();
		}

		@Override
		protected List<String> doInBackground(String... searchCriteria) {
			String required = searchCriteria[0];
			int numberOfWildcards = 0;
			while (required.indexOf("?") != -1) {
				numberOfWildcards++;
				required = required.replaceFirst("\\?", "");
			}
			for (int i=0; i<numberOfWildcards; i++)	required += "?"; 
			String prefix = searchCriteria[1];
			String middle = searchCriteria[2];
			String suffix = searchCriteria[3];
			List<String> results = new ArrayList<String>();
			for (int i = 0; i < resourcesToLookIn.length; i++) {
				String[] words = readFromFile(resourcesToLookIn[i]);
				for (int j = 0; j < words.length; j++) {
					if (j % 1000 == 0)
						publishProgress((int) ((100 * i) / resourcesToLookIn.length + 100 * (float) j
								/ (float) words.length / resourcesToLookIn.length));
					String word = words[j];
					if (word.startsWith(prefix) && word.endsWith(suffix) && word.contains(middle) && word.length() > 1
							&& word.length() <= required.length() && match(word, required)) {
						results.add(word);
					}
				}
				publishProgress(100 * (i + 1) / resourcesToLookIn.length);
			}
			Collections.sort(results, new Comparator<String>() {
				@Override
				public int compare(String string1, String string2) {
					return string2.length() - string1.length();
				}
			});
			return results;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			this.dialog.setProgress(values[0]);
		}

		@Override
		protected void onPostExecute(List<String> results) {
			super.onPostExecute(results);
			dialog.dismiss();
			ArrayAdapter<String> faceAdapter = new ArrayAdapter<String>(WordfindActivity.this,
					android.R.layout.simple_list_item_1, results);
			setListAdapter(faceAdapter);
		}
	}

	private String[] readFromFile(int resourceId) {
		InputStream is = getResources().openRawResource(resourceId);
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		List<String> wordslist = new ArrayList<String>();
		String strLine;
		try {
			while ((strLine = br.readLine()) != null) {
				wordslist.add(strLine);
			}
			br.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return wordslist.toArray(new String[0]);
	}

	private static boolean match(String word, String required) {
		if ("".equals(word) || word.equals(required) || required.equals("?"))
			return true;
		for (int i = 0; i < required.length(); i++) {
			String letter = "" + required.toCharArray()[i];
			if (word.startsWith(letter) || letter.equals("?")) {
				String subrequired = required.substring(0, i) + required.substring(i + 1, required.length());
				return match(word.substring(1), subrequired);
			}
		}
		return false;
	}
}